#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <unordered_map>
#include "Log.hpp"

using namespace log_ns;

const static std::string sep = ". ";

class Dict
{
private:
    void LoadDict(const std::string &path)
    {
        std::ifstream in(path); // 打开指定路径下的文件
        if (!in.is_open())
        {
            LOG(FATAL, "open %s failed!\n", path.c_str());
            exit(1);
        }

        std::string line;
        // 从文件里读，把内容放进line里面
        while (std::getline(in, line))
        {
            LOG(DEBUG, "load info: %s, success!", line.c_str());
            if (line.empty())
                continue;

            // 查找，再对一行内容进行分割
            auto pos = line.find(sep);
            if (pos == std::string::npos)
                continue; // 查到空行

            std::string key = line.substr(0, pos);
            if (key.empty())
                continue;
            std::string value = line.substr(pos + sep.size());
            if (value.empty())
                continue;

           // _dict.insert({key, value});
           _dict.insert(std::make_pair(key, value));
        }
        LOG(INFO, "load %s done!\n", path.c_str());

        in.close();
    }

public:
    Dict(const std::string &path) : _dict_path(path)
    {
        // 从配置文件里加载字典,并初始化
        LoadDict(_dict_path);
    }

    // 进行翻译
    std::string Translate(std::string word)
    {
        if(word.empty()) return "word empty None";
        auto iter = _dict.find(word);
        if(iter == _dict.end()) return "iter _dict endNone";
        else return iter->second;
    }
    ~Dict()
    {
    }

private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _dict_path; // 字典对应的路径
};